<template>
  <div class="whole-box" id="main">
    <div class="firtbox">
      <div class="btns">
        <template slot-scope="scope"></template>
        <el-button type="primary" plain size="small" @click="updateVisible = true">发布</el-button>
        <el-button type="warning" plain size="small" @click="saveVisible = true">保存</el-button>
        <el-button type="danger" plain size="small" @click="deletePaper()">删除</el-button>
      </div>
      <h5 class="firt-img">
        <i class="fa fa-cubes"></i> 试卷编辑
      </h5>
      <p class="firt-in">编辑您的试卷！</p>
    </div>
    <div class="secbox">
      <div contenteditable="true" class="secret" id="secret">绝密⭐️启用前</div>
      <div contenteditable="true" class="title" id="title">{{title}}</div>
      <br />
      <!-- <div contenteditable="true" font-size:15px class="type" id="type">试卷标题</div> -->
      <div contenteditable="true" class="remarks_type" id="remarks_type">
        本试卷共
        <span id="pages">5</span>
        页,
        <span id="number">{{number}}</span>
        题(含选考题)。满分
        <span id="total">{{scores}}</span>
        分。考试用时
        <span id="time">120</span>
        分钟。
      </div>
      <div contenteditable="true" class="good_luck" id="good_luck">⭐祝考试顺利⭐</div>
      <div contenteditable="true" class="main_remarks_title" id="main_remarks_title">注意事项：</div>
      <div contenteditable="true" class="main_remarks" id="main_remarks">
        <div class="each_remarks">1.答题前，先将自己的姓名、准考证号填写在试卷和答题卡上，并将准考证号条形码粘贴在答题卡上的指定位置。</div>
        <div class="each_remarks">2.选择题的作答：每小题选出答案后，用2B铅笔把答题卡上对应题目的答案标号涂黑。写在试卷、草稿纸和答题卡上的非答题区域均无效。</div>
        <div class="each_remarks">3.非选择题的作答：用黑色签字笔直接答在答题卡上对应的答题区域内。写在试卷、草稿纸和答题卡上的非答题区域均无效。</div>
        <div
          class="each_remarks"
        >4.选考题的作答：先把所选题目的题号在答题卡上指定的位置用2B铅笔涂黑。答案写在答题卡上对应的答案区域内，写在试卷、草稿纸和答题卡上的非答题区域均无效。</div>
        <div class="each_remarks">5.考试结束后，请将本试卷和答题卡一并上交。</div>
      </div>
      <div class="questions">
        <!-- :key=questionTypes.type.id -->
        <!-- --------------------------------------------------------- -->
        <!-- 可拖拽的可输入框 -->
        <div v-for="(item,index) in questionTypes" v-bind:key="index">
          <div class="questionBody">
            <div
              class="main_remarks_title"
            >{{index+1}}、{{item.type.type}}:本题共{{item.questionDetailRanks.length}}小题。</div>
            <draggable
              :list="questionTypes[index].questionDetailRanks"
              :disabled="!enabled"
              class="questiones-group"
              ghost-class="ghost"
              :move="checkMove"
              @start="dragging = true"
              @end="dragging = false"
            >
              <div
                v-for="(items,cindex) in questionTypes[index].questionDetailRanks"
                v-bind:key="cindex"
              >
                <div class="eachquestion" float="left">
                  <el-button
                    slot="append"
                    icon="el-icon-search"
                    @click="showDialog(item.type.id,items.id)"
                  ></el-button>
                  <div contenteditable="true" v-html="items.rankDetails">{{ items.rankDetails }}</div>
                </div>
              </div>
            </draggable>
          </div>
        </div>
      </div>
      <!-- 添加题目对话框 -->
      <el-dialog title="试题选择" :visible.sync="addDialogVisible" width="50%">
        <!-- 对话框内容-->
        <el-table
          :data="QuestionData"
          border
          :row-style="{height:'0px'}"
          :cell-style="{padding:'2px'}"
          highlight-current-row
          style="width: 100%"
        >
          <!--指定默认排序 按分值升序  -->
          <el-table-column prop="hardness.hardness" label="难度"></el-table-column>
          <el-table-column prop="student.student" label="适用对象"></el-table-column>
          <el-table-column label="考点">
            <template slot-scope="scope">
              <div v-for="item in scope.row.tags">{{item.tag}}</div>
            </template>
          </el-table-column>
          <el-table-column prop="questionType.type" label="题型"></el-table-column>
          <el-table-column label="操作" width="180px">
            <template slot-scope="scope">
              <el-button size="small" type="success" plain @click="viewQuestion(scope.row.id)">查看</el-button>
              <el-button
                size="small"
                type="primary"
                plain
                @click="chooseQuestion(scope.row.id,scope.row.detailid)"
              >选择</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 底部 -->
        <span slot="footer" class="dialog-footer">
          <el-button type="danger" @click="addDialogVisible=false">关 闭</el-button>
        </span>
      </el-dialog>
      <!-- 保存按钮dialog -->
      <el-dialog title="试题难度选择" :visible.sync="saveVisible" width="40%">
        <div>
          <el-radio v-model="hardness" label="1" border>低难度</el-radio>
          <el-radio v-model="hardness" label="2" border>中等难度</el-radio>
          <el-radio v-model="hardness" label="3" border>高难度</el-radio>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="saveVisible = false">取 消</el-button>
          <el-button type="primary" @click="savaPaper()">确定</el-button>
        </div>
      </el-dialog>
      <!-- 发布按钮dialog -->
      <el-dialog title="试题难度选择" :visible.sync="updateVisible" width="40%">
        <div>
          <el-radio v-model="hardness" label="1" border>低难度</el-radio>
          <el-radio v-model="hardness" label="2" border>中等难度</el-radio>
          <el-radio v-model="hardness" label="3" border>高难度</el-radio>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="updateVisible = false">取 消</el-button>
          <el-button type="primary" @click="updatePaper()">确定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import draggable from "vuedraggable";
import { getRequest } from "../utils/api";
import { postRequest } from "../utils/api";
import { postJsonRequest } from "../utils/api";
export default {
  name: "CreatPaper",
  components: {
    draggable
  },

  data() {
    return {
      // 拖拽相关
      enabled: true,
      dragging: false,
      //题目详细内容
      quescontent: "",
      //试卷名称
      title: "",
      //试题预置类型id
      pre_base_id: null,
      // 试卷难度
      hardness: null,
      number: "",
      scores: "",
      //所有题型（下涵盖其所有的具体内容））
      questionTypes: [],
      paper_id: null,
      questype: 1,
      //dialog设置不可见
      addDialogVisible: false,
      // 保存按钮
      saveVisible: false,
      // 更新按钮
      updateVisible: false,
      //根据类型type从后台获取的试题
      QuestionData: [],
      //考点
      tags: []
    };
  },
  mounted() {
    this.getData();
    // console.log(`渲染时打印TypeChoose传来的id`,this.$route.query.id)
    this.getPrebase();
    this.paper_id = this.pre_base_id;
  },
  methods: {
    // 拖拽
    checkMove: function(e) {
      window.console.log("Future index: " + e.draggedContext.futureIndex);
      console.log(`拖拽`);
    },
    // 获取前一页面传递的预置类型id
    getData() {
      // 在没有 => 此类函数时，无需使用 _this
      var _this = this;
      _this.pre_base_id = Number(this.$route.query.id);
      console.log(`getData`, _this.pre_base_id);
    },
    //删除试卷--对应试卷id
    deletePaper: function() {
      postJsonRequest("/paper/delete", { id: this.pre_base_id }).then(res => {
        var result = res.data;
      });
      //打印试卷id
    },
    // 保存试卷
    savaPaper: function() {
      var content = document.getElementById("main").innerHTML;
      if (this.hardness == null) {
        this.$message.error("未选择试卷难度！");
      } else {
        postJsonRequest("/paper/save", {
          // 预置类型
          preBase: { id: Number(this.pre_base_id) },
          // 试卷内容html
          content: content,
          owner: { id: 1 },
          // 试卷名称
          name: this.title,
          // 试卷难度
          hardness: { id: Number(this.hardness) }
        }).then(res => {
          var result = res.data;
          console.log(this.pre_base_id);
          console.log(`save结果`, result);
        });
        this.saveVisible = !this.saveVisible;
      }
    },
    // 更新试卷update
    updatePaper: function() {
      this.paper_id = this.pre_base_id;
      var content = document.getElementById("main").innerHTML;
      if (this.hardness == null) {
        this.$message.error("未选择试卷难度！");
      } else {
        postJsonRequest("/paper/update", {
          // 预置类型
          id: this.paper_id,
          preBase: { id: this.pre_base_id },
          // 试卷内容html
          content: content,
          owner: { id: 1 },
          // 试卷名
          name: this.title,
          // 试卷难度
          hardness: { id: this.hardness }
        }).then(res => {
          var result = res.data;
          console.log(`试卷id`, this.paper_id);
          console.log(`预置类型id`, this.pre_base_id);
          console.log(`save结果`, result);
        });
        this.updateVisible = !this.updateVisible;
      }
    },
    // 获取试卷难度
    getHardness: function() {
      getRequest("");
    },
    //根据预置类型id（prebase_id）渲染页面
    getPrebase: function() {
      postRequest(
        "/pre_base/get_pre_base?pre_base_id=" + this.pre_base_id
      ).then(res => {
        var result = res.data;
        console.log(`返回数据`, res.data);
        var number = 0; //题目数量
        var questionTypes = result.data.questionTypes; //所有的题型（下涵盖其所有的具体内容）
        for (var i = 0; i < questionTypes.length; i++) {
          for (
            var j = 0;
            j < questionTypes[i].questionDetailRanks.length;
            j++
          ) {
            // 为获取的试卷类型添加小题内容属性
            questionTypes[i].questionDetailRanks[j].rankDetails = "";
          }
          number += questionTypes[i].questionDetailRanks.length;
        }
        this.questionTypes = questionTypes;
        // this.questionTypes = result.data.questionTypes;
        console.log(`修改后`, this.questionTypes);
        this.title = result.data.name;
        this.number = number;
        this.scores = result.data.scores;
        // console.log(this.title);
      });
    },
    //控制试题选择框的显示与隐藏并且调用接口查询题目
    showDialog(id, detailid) {
      this.addDialogVisible = true;
      console.log(`大题id`, id);
      console.log(`小题id`, detailid);
      var that = this;
      getRequest("/question/default?type=" + id).then(res => {
        var result = res.data;
        //将返回数据绑定到QuestionData
        that.QuestionData = result.data;
        // 表格数据length
        for (let i = 0; i < that.QuestionData.length; i++) {
          that.QuestionData[i].detailid = detailid;
        }
        console.log(`试题`, that.QuestionData);
      });
    },
    // //dialog内获取的试题
    // getQuestion:function(){
    //   var _this = this;
    //   getRequest(' /question/default',{
    //     query: _this.questype
    //   }).then(
    //     res =>{
    //       var result =res.data;
    //       //将返回数据绑定到QuestionData
    //       _this.QuestionData =result.data
    //     }
    //   )
    // },
    //根据试题id查看详细内容===>新窗口查看？
    viewQuestion(id) {
      const { href } = this.$router.resolve({
        name: "试题详情",
        path: "/view_question",
        query: {
          id: id
          //id 为试题id
          // ViewQuestion中用this.$route.query.id 接收id
        }
      });
      //新窗口打开题目详情
      window.open(href, "blank");
      console.log(id);
    },
    // chooseQuestion选择题目添加至题目框
    chooseQuestion(id, detailid) {
      // 已经传入题目id,和预置类型中的题目id
      // console.log(detailid);
      for (let j = 0, len = this.QuestionData.length; j < len; j++) {
        console.log(`表格题目数量10`, len);
        // 在表格获取的数据技术上 遍历判断id 根据获取id获取内容
        if (id == this.QuestionData[j].id) {
          // m为试卷大题的题目数量，n是小题数目
          for (let m = 0; m < this.questionTypes.length; m++) {
            for (
              let n = 0;
              n < this.questionTypes[m].questionDetailRanks.length;
              n++
            ) {
              if (detailid == this.questionTypes[m].questionDetailRanks[n].id) {
                this.questionTypes[m].questionDetailRanks[
                  n
                ].rankDetails = this.QuestionData[j].questionContent;
              }
            }
          }
          console.log(`题目id`, this.QuestionData[j].id);
        }
      }
      // 填充题目后 关闭窗口
      this.addDialogVisible = false;
    }
  }
};
</script>

<style scoped>
.whole-box {
  width: 100%;
  display: flex;
  flex-direction: column;
  overflow: auto;
}
.firtbox {
  padding: 5px 0px 15px 5px;
  position: relative;
  text-align: left;
  background-color: #ffffff;
  margin: 5px 5px 5px 0px;
  height: 50px;
  width: 100%;
  box-sizing: border-box;
  box-align: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
}
.secbox {
  padding-top: 4px;
  /*position: relative;*/
  margin: 20px;
  height: auto;
  background-color: #ffffff;
  margin: 15px auto auto 0%;
  width: 100%;
  height: auto;
  border-radius: 2px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
}
.firt-img {
  font-weight: 500;
  font-size: 13px;
  margin: 0;
  padding: 0;
}
.firt-in {
  font-size: 10px;
  color: #777777;
  height: 7px;
  margin: 0;
  padding: 0;
}
.btns {
  float: right;
  margin-top: 5px;
  margin-right: 15px;
}
.secret {
  font-weight: bold;
  font-size: 8px;
  text-align: left;
}
.paper {
  border: 1px solid;
}
.title {
  font-size: 22px;
  text-align: center;
}
.each_remarks {
  text-align: left;
  font-size: 15px;
}
/* 题目部分--大题 */
.questionBody {
  margin: 3px;
  padding: 5px;
}
/* 每个小题 */
.eachquestion {
  text-align: left;
  margin: 3px;
}
/* 题目标题 */
.main_remarks_title {
  text-align: left;
  font-size: 15px;
}

/* 拖拽 */
.ghost {
  opacity: 0.5;
  background: #c8ebfb;
}
.type {
  font-weight: 500;
  font-size: 30px;
  text-align: center;
}
.remarks_type {
  text-indent: 2em;
}
.good_luck {
  font-weight: 800;
  font-size: 18px;
  text-align: center;
  font-family: "Baoli SC";
}
.main_remarks_title {
  font-weight: bold;
}
.each_remarks {
  text-indent: 2em;
}
/* dialog表格 */
.el-table td,
.el-table th {
  padding: 2px;
}
</style>